import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI, getUserInfoAPI, getUserRoutesAPI } from '@/api/user'
import router from '@/router'
import { routes, resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    routes: [...routes]
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    REMOVE_TOKEN(state) {
      state.token = ''
      removeToken()
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    REMOVE_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    SET_ROUTES(state, newroutes) {
      console.log(routes)
      state.routes = [...routes, ...newroutes]
      console.log(state.routes)
    }
  },
  actions: {
    async login(context, { username, password }) {
      const { token } = await loginAPI({ username, password })
      // console.log(token)
      context.commit('SET_TOKEN', token)
    },
    async getUserInfo(context) {
      const data = await getUserInfoAPI()
      console.log(data)
      context.commit('SET_USERINFO', data)
      return data
    },
    async getRoutes(context) {
      const routes = await getUserRoutesAPI()
      // console.log(routes)
      context.commit('SET_ROUTES', routes)
      return routes
    },
    logout(context) {
      context.commit('REMOVE_TOKEN')
      context.commit('REMOVE_USERINFO', {})
      // context.state.routes = [...routes]
      resetRouter()
      router.push('/login')
    }
  }
}
